package siemenss7smart

import (
	"encoding/binary"
	"math"
)

// TagGroup 是标签分组
type TagGroup struct {
	GroupName    string `json:"name"`
	GroupType    string `json:"mmtype"`
	Block        int
	BeginAddress int `json:"begin_address"`
	ReadCount    int `json:"read_count"`
	TagData      map[int]byte
	TagMap       map[string]Tag `json:"tag"`
	ReadBuffer   []byte
}

// Tag 是标签
type Tag struct {
	Name     string `json:"name"`
	Address  string `json:"address"`
	DataType string `json:"data_type"`
	Desc     string `json:"desc"`
}

// GetValue 获取TagGroup中指定地址的数据
func (t TagGroup) GetValue(address string) (string, error) {
	return "", nil
}

// SetData 设置固定位置的数据
func (t TagGroup) SetData(index int, bytes byte) {
	t.TagData[t.BeginAddress+index] = bytes
}

// GetBitData 获得字节指定位置的bool值
func (t TagGroup) GetBitData(address int, bitIndex int) int {
	b, ok := t.TagData[address]
	if ok {
		return int((b >> (bitIndex - 1)) & 1)
	}
	return -9999

}

// GetByteData 获取指定位置的byte数据
func (t TagGroup) GetByteData(address int) byte {
	b, ok := t.TagData[address]
	if ok {
		return b
	}
	return 255
}

// GetFloatData 获取指定位置的float数据
func (t TagGroup) GetFloatData(address int) float32 {
	if _, ok := t.TagData[address]; ok {
		value := []byte{t.TagData[address+3], t.TagData[address+2], t.TagData[address+1], t.TagData[address]}
		return math.Float32frombits(binary.LittleEndian.Uint32(value))
	}
	return -9999
}

// GetIntData 获取指定位置的int数据
func (t TagGroup) GetIntData(address int) int {
	if _, ok := t.TagData[address]; ok {
		value := []byte{t.TagData[address+3], t.TagData[address+2], t.TagData[address+1], t.TagData[address]}
		return int(binary.LittleEndian.Uint32(value))
	}
	return -9999

}

// GetShortValue 获取指定位置的int16数据
func (t TagGroup) GetShortValue(address int) int16 {
	if _, ok := t.TagData[address]; ok {
		value := []byte{t.TagData[address+1], t.TagData[address]}
		return int16(binary.LittleEndian.Uint16(value))
	}
	return -9999
}
